package com.at.state14;

import com.at.bean.WaterSensor;
import com.at.functions5.WaterSensorMapFunction3;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/9/30 20:22
 */
public class StateBackendDemo8 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        /**
         * TODO 代码中指定状态后端
         * 1、负责管理 本地状态
         * 2、hashmap
         *      存在 TM的 JVM的堆内存， 读写快，缺点是存不了太多（受限于TaskManager的内存）
         *   rocksdb
         *      存在 TM所在节点rocksdb数据库，存到磁盘中，  写--序列化，读--反序列化
         *      读写相对慢一些，可以存很大的状态
         *
         * 3、配置方式
         *   1）配置文件 默认值 flink-conf.yaml
         *   2）代码中指定
         *   3）提交参数指定
         *   flink run-application -t yarn-application
         *   -p 3
         *   -Dstate.backend.type=rocksdb
         *   -c 全类名
         *   jar包
         */
        // 1、使用 hashmap 状态后端
        HashMapStateBackend hashMapStateBackend = new HashMapStateBackend();
        env.setStateBackend(hashMapStateBackend);
        // 2、使用 rocksdb 状态后端
        EmbeddedRocksDBStateBackend embeddedRocksDBStateBackend = new EmbeddedRocksDBStateBackend();
        env.setStateBackend(embeddedRocksDBStateBackend);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 7777)
                .map(new WaterSensorMapFunction3())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((element, ts) -> element.getTs() * 1000L)
                );

        sensorDS.keyBy(r -> r.getId())
                .process(
                        new KeyedProcessFunction<String, WaterSensor, String>() {
                            ValueState<Integer> lastVcState;

                            @Override
                            public void open(Configuration parameters) throws Exception {
                                super.open(parameters);
                                lastVcState = getRuntimeContext().getState(new ValueStateDescriptor<>("lastVcState", Types.INT));
                            }

                            @Override
                            public void processElement(WaterSensor value, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                                Integer lastVc = lastVcState.value(); // 取出值状态里的数据

                                Integer vc = value.getVc();
                                if (lastVc != null) {
                                    if (Math.abs(vc - lastVc) > 10) {
                                        out.collect("传感器=" + value.getId() + "===>当前水位值=" + vc + ", 与上一条水位值=" + lastVc + ",相差超过10！！！");
                                    }
                                }

                                lastVcState.update(vc);
                            }
                        }
                )
                .print();

        env.execute();
    }
}
